package com.cn.demo.springboot.controller;

import java.util.List;

import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.demo.springboot.quartz.bo.InitJobBo;
import com.cn.demo.springboot.quartz.service.IJobService;
import com.cn.demo.springboot.quartz.service.ITriggerUtil;

@Controller
//@Slf4j
@RequestMapping("/quartz")
public class QuartzController {
	private final static Logger log = LoggerFactory.getLogger(QuartzController.class);
    @Autowired
    ITriggerUtil triggerUtil;
    @Autowired
    IJobService IJobService;
    /**
	 * tj
	 * 2018年12月5日 上午9:05:45
	 */
    @RequestMapping("/findAll")
    @ResponseBody
    public Object findAll() {
    	List<InitJobBo> allJob = IJobService.getAllJob();
    	return allJob;
	}
	
    /**
     * 修改Cron表达式
     * @param newCron
     * @param jobId
     * @return
     */
    @RequestMapping("/updateCron")
    @ResponseBody
    public Object quartz(String newCron,String jobId) {
    	try {
    		// 进行 cron 表达式校验一下,cron 表达式错误则抛出异常
    		CronScheduleBuilder.cronSchedule(new CronExpression("cronExpression"));
    		
			triggerUtil.updateCron(newCron, jobId);
		} catch (Exception e) {
			 return e.getMessage();
		}
        return "success";
    }

    /**
     * 启动或停止一个任务
     * @param boo
     * @param jobId
     * @return
     */
    @RequestMapping("/startOrStop")
    @ResponseBody
    public Object quartz(Boolean boo,String jobId) {
    	try {
    		triggerUtil.updateRunStatus(boo, jobId);
		} catch (Exception e) {
			 return e.getMessage();
		}
        return "success";
    }
    
    @RequestMapping("/nowExecute")
    @ResponseBody
    public Object nowExecute(String jobId) {
    	try {
    		triggerUtil.nowExecute(jobId);
		} catch (Exception e) {
			 return e.getMessage();
		}
        return "success";
    }
}
